// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import * as path from 'path';
import UserListViewProvider from './provider/UserListViewProvider';
import {LayoutPanel} from "./LayoutPanel";
import RequestHandle from './RequestHandle';

const express = require('express');
const bodyParser = require('body-parser');
const net = require('net')
const app = express();
const indexFilePath: string = 'dist';
const START_PORT = 4000;
const LOCAL_URL = 'http://localhost';
let mCurrentPort = START_PORT;
let mUserListProvider: UserListViewProvider;
const mRequestHandle = new RequestHandle();



// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {

	// Use the console to output diagnostic information (console.log) and errors (console.error)
	// This line of code will only be executed once when your extension is activated
	console.log('Congratulations, your extension "lty-plugin-lvgl" is now active!');

	// The command has been defined in the package.json file
	// Now provide the implementation of the command with registerCommand
	// The commandId parameter must match the command field in package.json
	let disposable = vscode.commands.registerCommand('lty-plugin-lvgl.helloWorld', () => {
		// The code you place here will be executed every time your command is executed

		// Display a message box to the user
		vscode.window.showInformationMessage('Hello World from lty-plugin-lvgl!');
	});

	let htmlPath = path.join(context.extensionPath, indexFilePath);
    app.use(express.static(htmlPath))
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({extended: false}));

    // @ts-ignore
    app.post('/index', function (req, res, next) {
        // let url = req.body.todo
        // 输出 JSON 格式
        // let response = {
        //     "first_name": 'test name',
        //     "last_name": 'test last name'
        // };
        // res.end(JSON.stringify(response));
        mRequestHandle.handel(req, res, next);
    })

    portIsOccupied(START_PORT)
        .then(port => {
            app.listen(port, () => {
                mCurrentPort = port as number;
                console.log(`start http://localhost:${port}`);
                LayoutPanel.register(mCurrentPort, context)
            })
        })

    context.subscriptions.push(disposable);
}

function portIsOccupied(port: number) {
    const server = net.createServer().listen(port)
    return new Promise((resolve, reject) => {
        server.on('listening', () => {
            console.log(`the server is runnint on port ${port}`)
            server.close()
            resolve(port)
        })

        server.on('error', (err: any) => {
            if (err.code === 'EADDRINUSE') {
                resolve(portIsOccupied(port + 1));
                console.log(`this port ${port} is occupied, try another.`)
            } else {
                reject(err)
            }
        })
    })
}

// this method is called when your extension is deactivated
export function deactivate() {}
